/**
 * 功能描述
 *
 * @author: yekongyu
 * @date: 2023年01月10日 9:01
 */
package com.jiansu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiansu.entity.UnitDimension;
import com.jiansu.service.OcrImagesService;
import com.jiansu.util.HttpUtil;
import com.jiansu.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

import static com.jiansu.util.DocumentUtil.getPictureFromPdf;

@Service
public class OcrImagesServiceImpl implements OcrImagesService {

    @Value("${file.uploadFilePath}")
    private String savePath;
    @Value("${file.url}")
    private String url;
    @Value("${file.accessToken}")
    private String accessToken;

    @Override
    public Result<UnitDimension> ocrImagesDiff(MultipartFile file) throws Exception {
        //获取文件名称
        String filename = file.getOriginalFilename();
        assert filename != null;
        String extName = filename.substring(filename.lastIndexOf("."));

        //判断该文件是否是word文件
        if (!".pdf".equals(extName) && !".PDF".equals(extName)) {
            return Result.error(300, "只支持pdf文件上传");
        }

        UnitDimension unitDimension = new UnitDimension();
        unitDimension.setFileName(filename);

        String filePath = savePath + UUID.randomUUID() + File.separator;
        File fil = new File(filePath);
        if (!fil.exists()) {
            fil.mkdirs();
        }
        String newPath = filePath + filename;
        try {
            file.transferTo(new File(newPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!new File(newPath).exists()) {
            return Result.error("文件保存失败！！！");
        }

        List<String> pictureFromBase64 = getPictureFromPdf(newPath);

        System.out.println(pictureFromBase64.size());
        System.out.println("中间交工证书：" + filename);
        for (String bear64 : pictureFromBase64) {
            String b64 = "data:image/jpg;base64," + bear64;
            String img = URLEncoder.encode(b64, "UTF-8");
            String param = "image=" + img;
            String result = HttpUtil.post(url, accessToken, param);
            JSONObject object = JSONObject.parseObject(result);
            JSONArray wordsResult = object.getJSONArray("words_result");
            if (wordsResult == null) {
                break;
            }
            for (int i = 0; i < wordsResult.size(); i++) {
                String words = wordsResult.getJSONObject(i).getString("words");
                String str = words.replace(" ", "");
                if (i < 10 && "中间交工证书".equals(str)) {
                    unitDimension.setBase64(b64);
                    unitDimension.setTableName(str);
                    for (int j = i + 1; j < wordsResult.size(); j++) {
                        String word = wordsResult.getJSONObject(j).getString("words");
                        String companyStr = null;
                        if (word.lastIndexOf(":") != -1) {
                            companyStr = word.substring(word.lastIndexOf(":") + 1);
                        }
                        String string = word.replace(" ", "");
                        String content = null;
                        if (wordsResult.size() > j + 1) {
                            content = wordsResult.getJSONObject(j + 1).getString("words");
                        }
                        if ("项目名称".equals(string) || string.contains("项目名称") && unitDimension.getEntryName() == null) {
                            if (string.length() != 4) {
                                unitDimension.setEntryName(strSub(word, "称"));
                                continue;
                            }
                            unitDimension.setEntryName(content);
                            System.out.println("项目名称：" + content);
//                            continue;
                        } else if ("施工单位".equals(string) || string.contains("施工单位") && unitDimension.getConstructionUnit() == null) {
                            if (string.length() != 4) {
                                String a = strSub(word, "位");
                                unitDimension.setConstructionUnit(a);
                                continue;
                            }
                            unitDimension.setConstructionUnit(content);
                            System.out.println("施工单位：" + content);
//                            continue;
                        } else if ("合同段".equals(string) || string.contains("合同段") && unitDimension.getContract() == null) {
                            if (string.length() != 3) {
                                unitDimension.setContract(strSub(word, "段"));
                                continue;
                            }
                            unitDimension.setContract(content);
                            System.out.println("合同段：" + content);
//                            continue;
                        } else if ("监理单位".equals(string) || string.contains("监理单位") && unitDimension.getSupervisor() == null) {
                            if (string.length() != 4) {
                                unitDimension.setSupervisor(strSub(word, "位"));
                                continue;
                            }
                            unitDimension.setSupervisor(content);
                            System.out.println("监理单位：" + content);
//                            continue;
                        } else if ("单位工程".equals(string) || string.contains("单位工程：") || string.contains("单位工程:")) {
                            if (companyStr != null) {
                                unitDimension.setUnitProject(companyStr);
                                System.out.println("单位工程：" + companyStr);
                            } else {
                                if (string.length() == 4) {
                                    unitDimension.setUnitProject(content);
                                    continue;
                                }
                                String companyStr1 = word.substring(word.lastIndexOf("：") + 1);
                                if (companyStr1.length() < 1) {
                                    unitDimension.setUnitProject(content);
                                    System.out.println("单位工程：" + content);
                                } else {
                                    unitDimension.setUnitProject(companyStr1);
                                    System.out.println("单位工程：" + companyStr1);
                                }
                            }
//                            continue;
                        } else if ("分部工程".equals(string) || string.contains("分部工程：") || string.contains("分部工程:")) {
                            if (companyStr != null) {
                                unitDimension.setPartProjec(companyStr);
                                System.out.println("项目名称：" + companyStr);
                            } else {
                                if (string.length() == 4) {
                                    unitDimension.setPartProjec(content);
                                    continue;
                                }
                                String companyStr1 = word.substring(word.lastIndexOf("：") + 1);
                                if (companyStr1.length() < 1) {
                                    unitDimension.setPartProjec(content);
                                    System.out.println("部分工程：" + content);
                                } else {
                                    unitDimension.setPartProjec(companyStr1);
                                    System.out.println("部分工程：" + companyStr1);
                                }
                            }
//                            continue;
                        } else if ("分项工程".equals(string) || string.contains("分项工程：") || string.contains("分项工程:")) {
                            if (companyStr != null) {
                                unitDimension.setSubWorks(companyStr);
                                System.out.println("分项工程：" + companyStr);
                            } else {
                                if (string.length() == 4) {
                                    unitDimension.setSubWorks(content);
                                    continue;
                                }
                                String companyStr1 = word.substring(word.lastIndexOf("：") + 1);
                                if (companyStr1.length() < 1) {
                                    unitDimension.setSubWorks(content);
                                    System.out.println("分项工程：" + content);
                                } else {
                                    unitDimension.setSubWorks(companyStr1);
                                    System.out.println("分项工程：" + companyStr1);
                                }
                            }
//                            break;
                        }
                    }
                    break;
                }
            }
        }
        if (unitDimension.getSubWorks() == null) {
            unitDimension.setSubWorks("无");
        }
        if (unitDimension.getConstructionUnit() == null) {
            unitDimension.setConstructionUnit("无");
        }
        if (unitDimension.getContract() == null) {
            unitDimension.setContract("无");
        }
        if (unitDimension.getSupervisor() == null) {
            unitDimension.setSupervisor("无");
        }
        if (unitDimension.getUnitProject() == null) {
            unitDimension.setUnitProject("无");
        }
        if (unitDimension.getPartProjec() == null) {
            unitDimension.setPartProjec("无");
        }
        if (unitDimension.getSubWorks() == null) {
            unitDimension.setSubWorks("无");
        }
        unitDimension.setContentClass(unitDimension.getEntryName() + " " + unitDimension.getContract() + " " + unitDimension.getUnitProject() + " " + unitDimension.getPartProjec() + " " + unitDimension.getTableName());

        return Result.ok(unitDimension);
    }

    public String strSub(String str, String indexStr) {
        if (str.lastIndexOf(indexStr) != -1) {
            return str.substring(str.indexOf(indexStr) + 1);
        }
        return str;
    }
}
